package com.lx.util;

import java.util.Date;
import java.util.UUID;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {
    // 密钥
    public static final String SECRET = "ff82854752c9d95afb57290fd7b9025af9ff3ee416c889c3870beacc290ca249";

    //间隔时间 单位分钟
    public static final Integer INTERVAL = 30;

    //生成token
    public static String createToken(Integer userID) {
        Date latDate = new Date();
        Date expDate = new Date(latDate.getTime()+INTERVAL*60*1000);

        return JWT.create()
                .withJWTId(UUID.randomUUID().toString())
                .withIssuedAt(latDate) //jwt生成的时间
                .withExpiresAt(expDate)//jwt过期的时间
                .withClaim("userID", userID)//向jwt中添加数据，可以添加多个，可被调用多次
                .sign(Algorithm.HMAC256(SECRET));//添加签名
    }

    //根据token验证是否有效
    public static DecodedJWT verifyToken(String token) {
        DecodedJWT decodedJwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJwt;
    }

    //读取jwt中存储数据
    public static Integer getUserID(String token) {
        return verifyToken(token).getClaim("userID").asInt();
    }

    //获取到期时间
    public static Date getExpires(String token) {
        return verifyToken(token).getExpiresAt();
    }
}
